package jp.co.google.ben.picasa.server;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
import com.google.appengine.repackaged.org.apache.commons.logging.Log;
import com.google.appengine.repackaged.org.apache.commons.logging.LogFactory;

public class AuthFilter implements Filter{
	private final static Log log = LogFactory.getLog(AuthFilter.class);
	public void destroy() {
		// TODO Auto-generated method stub
		
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub
		
	}

	public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
		log.debug("doFilter begin");
		UserService userService = UserServiceFactory.getUserService();
		User user = userService.getCurrentUser();
		log.debug("User " + user);
		if(user == null){
			String loginUrl = userService.createLoginURL(((HttpServletRequest)req).getRequestURL().toString());
			log.debug("loginUrl : " + loginUrl);
			((HttpServletResponse)resp).sendRedirect(loginUrl);
		}
		chain.doFilter(req, resp);
		log.debug("doFilter end");
	}

}
